#include<graphics.h>
#include<conio.h>
#define high 400
#define width 600
#pragma comment(lib,"Winmm.lib")

IMAGE img_bk,img_bd1,img_bd2,img_bar_up1,img_bar_up2,img_bar_down1,img_bar_down2;
int bird_x,bird_y;//小鸟坐标
int bar_up1_x,bar_up2_x,bar_up1_y,bar_up2_y;//上一半柱子坐标
int bar_down1_x,bar_down1_y,bar_down2_x,bar_down2_y;//下一半柱子坐标
int score;
//初始化数据
void starup()
{
	mciSendString("open E:\\background.mp3 alias bkmusic",NULL,0,NULL);
	mciSendString("play bkmusic repeat",NULL,0,NULL);
	initgraph(high,width);
	loadimage(&img_bk,"E:\\background.jpg");//读取背景图片
	loadimage(&img_bd1,"E:\\bird1.jpg");
	loadimage(&img_bd2,"E:\\bird2.jpg");//读取小鸟图片
	loadimage(&img_bar_up1,"E:\\bar_up1.gif");
	loadimage(&img_bar_up2,"E:\\bar_up2.gif");//读取柱子图片
	loadimage(&img_bar_down1,"E:\\bar_down1.gif");
	loadimage(&img_bar_down2,"E:\\bar_down2.gif");
	bird_x=30;
	bird_y=200;
	bar_up1_x=150;bar_up1_y=-300;
	bar_up2_x=150;bar_up2_y=-300;
	bar_down1_x=150;bar_down1_y=400;
	bar_down2_x=150;bar_down2_y=400;
	score=0;
	BeginBatchDraw();
}
//画面显示
void show()
{
	putimage(0,0,&img_bk);//绘制背景图片
	//绘制小鸟图像
	putimage(bird_x,bird_y,&img_bd1,NOTSRCERASE);
	putimage(bird_x,bird_y,&img_bd2,SRCINVERT);
	//绘制上一半柱子图片
	putimage(bar_up1_x,bar_up1_y,&img_bar_up1,NOTSRCERASE);
	putimage(bar_up2_x,bar_up2_y,&img_bar_up2,SRCINVERT);
	//绘制下一半柱子
	putimage(bar_down1_x,bar_down1_y,&img_bar_down1,NOTSRCERASE);
	putimage(bar_down2_x,bar_down2_y,&img_bar_down2,SRCINVERT);

	FlushBatchDraw();
	Sleep(50);
}
//与输入无关的更新
void updateWithoutInput()
{
	if(bird_y<580)
		bird_y=bird_y+3;
	//如果碰到柱子或者穿过柱子
	if(bird_x==bar_up1_x)//小鸟坐标和柱子坐标相等
	{
		if(bird_y>bar_up1_y && bird_y<bar_down1_y && bird_y>bar_up2_y && bird_y<bar_down2_y)
			score++;
		else
		{
			exit(0);
		}
	}

	if(bird_y==high+1)
	{
		exit(0);
	}
	if(bar_up1_x>0 || bar_down1_x>0 )
	{
        bar_up1_x--;
		bar_up2_x--;
		bar_down1_x--;
		bar_down2_x--;
	}
	else if(bar_up1_x<=0 && bar_down1_x<=0)
	{
		bar_up1_x=width;
		bar_up2_x=width;
	    int randPosition=rand()%(width-5);
		bar_up1_x=randPosition;
		bar_up2_x=randPosition;
		bar_down1_x=randPosition+width/4;
		bar_down2_x=randPosition+width/4;
	}
//	Sleep(3);

}
//与输入有关的更新
void updateWithInput()
{	
	char input;
	if (kbhit())
	{
		input=getch();
		if(input==' ' && bird_y>20)
		{
			bird_y=bird_y-30;
			mciSendString("close jpmusic",NULL,0,NULL);
			mciSendString("open E:\\Jump.mp3 alias jpmusic",NULL,0,NULL);
			mciSendString("play jpmusic",NULL,0,NULL);
		}
	}
}
void gameover()
{
	EndBatchDraw();
	getch();
	closegraph();
}
//主函数
int main()
{
	starup();
	while(1)
	{
		show();
		updateWithoutInput();
		updateWithInput();
	}
	gameover();
	return 0;
}